/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.gadgets.personalNotes.client;

import com.gadglet.client.gwt.GadgetUtils;
import com.gadglet.client.gwt.core.GadgletQuery;
import com.gadglet.client.gwt.core.GadgletRequest;
import com.gadglet.client.gwt.core.GadgletResponse;
import com.gadglet.client.gwt.ui.DebugDialogBox;
import com.gadglet.client.gwt.ui.HomeViewMainPanel;
import com.gadglet.client.gwt.ui.SimpleDialogBox;
import com.gadglet.client.gwt.ui.UIUtils;
import com.gadglet.gadgets.personalNotes.shared.Params;
import com.gadglet.params.ProfileFields;
import com.gadglet.params.ReqActionTypes;
import com.gadglet.params.ReqTypes;
import com.gadglet.params.SortTypes;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.gadgets.client.ContentSection;
import com.google.gwt.gadgets.client.Gadget.ContentType;
import com.google.gwt.gadgets.client.Gadget.InjectContent;
import com.google.gwt.gadgets.client.PreferencesFeature;
import com.google.gwt.gadgets.client.PreferencesProvider;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * The Gadget Home view 
 * <p>
 * In this view user can:
 * <li> Edit profile
 * <li> Invite and accept friends
 * <li> Add personal notes
 * <li> Delete personal notes
 *
 */
@InjectContent(files = "home.html")
@ContentType(type = "html", views = { "home", "default" })
public class PersonalNotesHomeView extends ContentSection<PersonalNotesGadget> {

	private DebugDialogBox debug = null;

	/**
	 *  Query object use to create a request for personal notes
	 *  The definition "ReqTypes.MINGLET" will create requests to the
	 *  Minglets Servlet 
	 */
	final GadgletQuery viewPersonalNotesQry = new GadgletQuery(ReqTypes.MINGLET);
	/**
	 * Request object used to send and a request to the gadget server
	 * and process the results
	 */
	final ViewPersonalNotes viewPersonalNotesRequest = new ViewPersonalNotes(
			viewPersonalNotesQry);

	/**
	 * Query object used to build "add",  and "delete" requests
	 * The definition "ReqTypes.MINGLET" will create requests to the
	 *  Minglets Servlet 
	 */
	final GadgletQuery changePersonalNoteQry = new GadgletQuery(
			ReqTypes.MINGLET);
	
	/**
	 * Request object used for "add" and "delete" requests
	 */
	final GadgletRequest changePersonalNoteRequest = new ChangePersonalNotes(
			changePersonalNoteQry);

	final Grid results = new Grid();
	protected final HorizontalPanel paging = new HorizontalPanel();

	final Button prevButton = new Button();
	final Button nextButton = new Button();
	final PreferencesFeature  prefsUtils = PreferencesProvider.get();
	final SimpleDialogBox serverMessage = SimpleDialogBox
			.getMesseageDialogBox();

	@Override
	public void init(PersonalNotesGadget gadget) {

		debug = DebugDialogBox.getErrorNotifier();

		prevButton.setText(prefsUtils.getMsg("gadgetLabelPrevious"));
		nextButton.setText(prefsUtils.getMsg("gadgetLabelNext"));

		final HomeViewMainPanel mainPanel = new HomeViewMainPanel();

		final HorizontalPanel addItemPanel = new HorizontalPanel();
		final DisclosurePanel addDisclosurePanel = new DisclosurePanel(
				prefsUtils.getMsg("gadgetLabelAdd"));
		final TextArea message = new TextArea();

		final VerticalPanel priority = new VerticalPanel();
		final RadioButton highPriority = new RadioButton("priorityFilter",
				prefsUtils.getMsg("gadgetLabelHigh"));
		final RadioButton medPriority = new RadioButton("priorityFilter",
				prefsUtils.getMsg("gadgetLabelMedium"));
		final RadioButton lowPriority = new RadioButton("priorityFilter",
				prefsUtils.getMsg("gadgetLabelLow"));
		lowPriority.setValue(true);
		priority.add(highPriority);
		priority.add(medPriority);
		priority.add(lowPriority);

		final Button saveButton = new Button(
				prefsUtils.getMsg("gadgetLabelSave"));

		final PrioritySelection selection = new PrioritySelection(
				viewPersonalNotesQry, viewPersonalNotesRequest);
		addItemPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM);
		addItemPanel.add(message);
		addItemPanel.add(new HTML("&nbsp;"));
		addItemPanel.add(priority);
		addItemPanel.add(new HTML("&nbsp;"));
		addItemPanel.add(saveButton);

		addDisclosurePanel.add(addItemPanel);
		addDisclosurePanel.setHeader(new HTML(prefsUtils
				.getMsg("gadgetLabelAdd")));

		mainPanel.add(addDisclosurePanel);

		mainPanel.add(selection.getPanel());

		mainPanel.add(results);

		RootPanel.get().add(mainPanel.getGadgetPanel());

		saveButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				changePersonalNoteQry.setRequestAction(ReqActionTypes.ADD);
				changePersonalNoteQry.clearParamList();

				String priority = "";
				if (highPriority.getValue())
					priority = "1";
				else if (medPriority.getValue())
					priority = "2";
				else
					priority = "3";

				changePersonalNoteQry.addParam(Params.PRIORITY.getParamName(),
						priority);
				changePersonalNoteQry.addParam(Params.MESSAGE.getParamName(),
						message.getValue());

				changePersonalNoteRequest.makeRequest();
				message.setValue("");

			}
		});

		viewPersonalNotesQry.setRequestAction(ReqActionTypes.VIEW);
		viewPersonalNotesQry.addSortBy("creation", SortTypes.ASC);
		viewPersonalNotesQry
				.setReturnField("personalNotesMessage,creation");
		viewPersonalNotesQry.setStartItemsFrom(0);
		viewPersonalNotesQry.setItemsNum(5);
		viewPersonalNotesRequest.makeRequest();

		prevButton.setVisible(false);
		prevButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				viewPersonalNotesQry.setStartItemsFrom(viewPersonalNotesQry
						.getStartFrom() - viewPersonalNotesQry.getItemNum());
				viewPersonalNotesRequest.makeRequest();

			}

		});
		paging.add(prevButton);

		nextButton.setVisible(false);
		nextButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				viewPersonalNotesQry.setStartItemsFrom(viewPersonalNotesQry
						.getStartFrom() + viewPersonalNotesQry.getItemNum());
				viewPersonalNotesRequest.makeRequest();

			}

		});
		paging.add(nextButton);

	}

	public class ViewPersonalNotes extends GadgletRequest {
		GadgletResponse jResponse;

		ViewPersonalNotes(GadgletQuery req) {
			super(req);

		}

		@Override
		protected void processResults(GadgletResponse data) {
			jResponse = data;

			if (jResponse.isSuccessful()) {

				DeleteImage deleteImage = null;
				results.resize(1, 4);
				results.clear();
				int index;
				for (index = 0; index < jResponse.getRootItemsNum(); index++) {

					JSONObject item = data.getItem(index);

					results.setWidget(
							index,
							0,
							new Image(GadgetUtils.getGadgetIconURL(jResponse
									.getStringItemValue(
											Params.PRIORITY.getParamName(),
											index), null, false)));
					results.setWidget(
							index,
							1,
							new HTML(jResponse.getStringItemValue(
									Params.MESSAGE.getParamName(), index)));

					if (data.isDeletePermitted(index)) {

						deleteImage = new DeleteImage(
								GadgetUtils.getGadgetIconURL("delete", null,
										false),
								jResponse.getItemKeyValue(index));

						deleteImage.addClickHandler(new ClickHandler() {
							@Override
							public void onClick(ClickEvent event) {
								changePersonalNoteQry.clearParamList();
								changePersonalNoteQry
										.setRequestAction(ReqActionTypes.DELETE);
								changePersonalNoteQry
										.setRequestItemkey(((DeleteImage) event
												.getSource()).getItemID());
								changePersonalNoteRequest.makeRequest();

							}

						});
						results.setWidget(index, 2, deleteImage);
					}
					else{
						String nick = data.getStringItemValue(ProfileFields.PROFILE_NICKNAME.getParamName(),index);
						
						HorizontalPanel profile = new HorizontalPanel();
						if(nick!=null){
							profile.add(new HTML(prefsUtils.getMsg("gadgetLabelSharedBy")+":"));
							profile.add(UIUtils.getSpace());
							profile.add(new Label(nick));

						}
											
						results.setWidget(index, 2, profile);
						
					}
					results.resize(index + 3, 4);

				}

				if (viewPersonalNotesQry.getStartFrom() > 0)
					prevButton.setVisible(true);
				else
					prevButton.setVisible(false);

				if (jResponse.hasMoreItems())
					nextButton.setVisible(true);
				else
					nextButton.setVisible(false);

				results.setWidget(index, 0, paging);

			}

			else {
				debug.showError(1, jResponse.getError());
			}

		}
	}

	public class ChangePersonalNotes extends GadgletRequest {
		ChangePersonalNotes(GadgletQuery req) {
			super(req);
		}

		@Override
		protected void processResults(GadgletResponse data) {
			GadgletResponse jResponse = data;

			if (jResponse.isSuccessful()) {
				// reffresh
				viewPersonalNotesRequest.makeRequest();
			} else {

				serverMessage
						.showError(prefsUtils.getMsg(jResponse.getError()));
			}

		}
	}

}
